package com.yl.common.control

import com.yl.common.getContext
import com.yl.common.utils.generateToken
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice

/**
 *
 * create by 2021/5/11.
 * @author udbjqr
 */
@ControllerAdvice
class ResponseAdvice : ResponseBodyAdvice<Any> {
	@Value("\${config.token-key}")
	private lateinit var key: String

	@Value("\${config.expires-time}")
	private var expiresTime: Long = 0

	companion object {
		private val log = LoggerFactory.getLogger(ResponseAdvice::class.java)
	}

	override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean {
		return true
	}

	override fun beforeBodyWrite(
		body: Any?,
		returnType: MethodParameter,
		selectedContentType: MediaType,
		selectedConverterType: Class<out HttpMessageConverter<*>>,
		request: ServerHttpRequest,
		response: ServerHttpResponse
	): Any? {
		response.headers.set("Token", generateToken(expiresTime, key))
		log.debug("返回:{}", body.toString())

		return if (body is ResponseBody)
			handleUserViewColumn(getContext().userId,body)
		else body
	}

}

var handleUserViewColumn = fun (_:Long,body : ResponseBody) : ResponseBody {
	return body
}